package com.sunday.pinxinghui.model.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.AddressListAdapter;
import com.sunday.pinxinghui.adapter.ServicePlaceAdapter;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.IndexProduct;
import com.sunday.pinxinghui.entity.ServicePlace;
import com.sunday.pinxinghui.network.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/22.
 */

public class ServicePlaceListActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.checkbox_select_all)
    CheckBox checkboxSelectAll;
    @Bind(R.id.bottom_menu)
    RelativeLayout bottomMenu;

    private int addressId;
    private List<ServicePlace> dataSet = new ArrayList<>();
    private String lng, lat;
    private boolean isFromSelect;
    private ServicePlaceAdapter adapter;
    private int servicePlaceId;
    private ServicePlace servicePlace;
    private int isSelf;//是否自提 0：否 1：是
    private int cityId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_list);
        ButterKnife.bind(this);
        addressId = getIntent().getIntExtra("addressId", 0);
        isFromSelect = getIntent().getBooleanExtra("isFromSelect", false);
        if (isFromSelect) {
            titleView.setText("选择配送点");
            bottomMenu.setVisibility(View.VISIBLE);
            lat = null;
            lng = null;
        } else {
            titleView.setText("配送点");
            bottomMenu.setVisibility(View.GONE);
            lat = SharePerferenceUtils.getIns(mContext).getString("latitude", "");
            lng = SharePerferenceUtils.getIns(mContext).getString("longitude", "");
            cityId = BaseApplication.getInstance().getCityId();
        }
        initRecyclerView();
        getData();

    }

    private void initRecyclerView() {
        emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new ServicePlaceAdapter(mContext, dataSet, isFromSelect);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.horizontal_space_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        checkboxSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isSelf = isChecked ? 1 : 0;
            }
        });
        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                adapter.setSelectIndex(p);
                adapter.notifyDataSetChanged();
                servicePlace = dataSet.get(p);
            }
        });


    }

    @OnClick(R.id.btn_buy)
    void onClick() {
        //返回是否是自提及服务点id
        Intent intent = new Intent();
        intent.putExtra("servicePlace", servicePlace);
        intent.putExtra("isSelf", isSelf);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<ServicePlace>>> call = ApiClient.getApiAdapter().getService(addressId == 0 ? null : addressId, lng, lat, cityId == 0 ? null : cityId);
        call.enqueue(new Callback<ResultDO<List<ServicePlace>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<ServicePlace>>> call, Response<ResultDO<List<ServicePlace>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                ResultDO<List<ServicePlace>> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    dataSet.clear();
                    if (isFromSelect) {
                        if (resultDO.getResult().size() > 2) {
                            dataSet.addAll(resultDO.getResult().subList(0, 2));
                        } else {
                            dataSet.addAll(resultDO.getResult());
                        }
                    } else {
                        dataSet.addAll(resultDO.getResult());
                    }

                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        adapter.setSelectIndex(0);
                        servicePlace = dataSet.get(0);
                    } else {
                        emptyLayout.setNoDataContent("该城市暂无入驻的配送点\n系统默认发货方式为快递");
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<ServicePlace>>> call, Throwable t) {
                dissMissDialog();
                ptrFrame.refreshComplete();
            }
        });
    }


}
